package exebuilder.helper;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.utils.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ZipHelper {
  public static void unzip(String zipFile, String destDir) {
    File file;
    try (ArchiveInputStream i = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, Files.newInputStream(Paths.get(zipFile)))) {
      ArchiveEntry entry;
      while ((entry = i.getNextEntry()) != null) {
        if (!i.canReadEntryData(entry)) {
          continue;
        }
        file = new File(destDir, entry.getName());
        if (entry.isDirectory()) {
          if (!file.isDirectory() && !file.mkdirs()) {
            throw new IOException("failed to create directory " + file);
          }
        } else {
          File parent = file.getParentFile();
          if (!parent.isDirectory() && !parent.mkdirs()) {
            throw new IOException("failed to create directory " + parent);
          }
          try (OutputStream o = Files.newOutputStream(file.toPath())) {
            IOUtils.copy(i, o);
          }
        }
      }
    } catch (IOException | ArchiveException e) {
      e.printStackTrace();
    }

  }
}
